﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;

namespace Fusion
{
	public class Animation
	{
		public AnimationData data;

		public int Frame
		{
			get
			{
				if( data == null )
					return 0;
				else
					return data.indices[frameIndex];
			}
		}
		public int frameIndex;
		public int frameTick;
		public int loopCounter;

		bool playing;
		public bool finished;

		public Animation()
		{
			Engine.AnimationTicker.Tick += Tick;
		}
		~Animation()
		{
			Engine.AnimationTicker.Tick -= Tick;
		}

		public void Play( String animationName )
		{
			AnimationData anim = Engine.AnimationData.Get( animationName );
			if( data == null || anim != data )
				Start( anim );
			else
				playing = true;

			finished = false;
		}
		public void Start( String animationName )
		{
			Start( Engine.AnimationData.Get( animationName ) );
		}
		public void Start( AnimationData Data )
		{
			data = Data;
			frameIndex = 0;
			frameTick = 0;
			loopCounter = 0;
			playing = true;
			finished = false;
		}

		public void Stop()
		{
			frameTick = 0;
			playing = false;
		}


		void Tick()
		{
			if( data == null || playing == false )
				return;

			// Increment frame
			frameTick++;
			if( frameTick >= data.delays[frameIndex] )
			{
				frameTick -= data.delays[frameIndex];
				frameIndex++;
			}

			// loop
			if( frameIndex >= data.indices.Count )
			{
				if( data.loopback >= 0 && ( data.loopcount < 0 || loopCounter < data.loopcount ) )
				{
					frameIndex = data.loopback;
					loopCounter++;
				}
				else
				{
					frameIndex--;
					Stop();
					finished = true;
				}
			}
		}
	}
}
